package com.ruoyi.quality.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.baseData.mapper.MaterialTypeMapper;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.utils.sql.QueryHelp;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.quality.domain.*;
import com.ruoyi.quality.domain.InspectionTask;
import com.ruoyi.quality.domain.dto.InspectionTaskDto;
import com.ruoyi.quality.domain.dto.InspectionTaskTemplateSamplingItemDto;
import com.ruoyi.quality.domain.dto.InspectionTaskValueDto;
import com.ruoyi.quality.domain.vo.InspectionTaskValueVo;
import com.ruoyi.quality.domain.vo.InspectionTaskVo;
import com.ruoyi.quality.domain.vo.InspectionTaskVo;
import com.ruoyi.quality.domain.vo.InspectionTemplateItemVo;
import com.ruoyi.quality.mapper.*;
import com.ruoyi.quality.service.InspectionTaskService;
import com.ruoyi.quality.mapper.InspectionTaskMapper;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class InspectionTaskServiceImpl implements InspectionTaskService{

    @Resource
    InspectionTaskMapper inspectionTaskMapper;

    @Resource
    InspectionTemplateItemMapper inspectionTemplateItemMapper;


    @Resource
    InspectionTaskValueMapper inspectionTaskValueMapper;

    @Resource
    SamplingItemMapper samplingItemMapper;

    @Resource
    InspectionTaskTemplateSamplingItemMapper inspectionTaskTemplateSamplingItemMapper;


    @Resource
    MaterialTypeMapper materialTypeMapper;

    @Resource
    SamplingMapper samplingMapper;

    @Resource
    InspectionTemplateMapper inspectionTemplateMapper;

    @Resource
    InspectionTemplateMaterialMapper inspectionTemplateMaterialMapper;


    @Override
    public Page<InspectionTaskVo> getInspectionTaskByPage(InspectionTaskDto pageEntity) {
        MPJLambdaWrapper<InspectionTask> wrapper = new MPJLambdaWrapper<InspectionTask>()
                .selectAll(InspectionTask.class)//查询user表全部字段
//                .selectAs( InspectionTemplate::getName, InspectionTaskVo::getInspectionTemplateName )
                //记的测试阶段
                .eq(InspectionTask::getDelFlag, 0)
//                .leftJoin(InspectionTemplate.class, InspectionTemplate::getId, InspectionTask::getInspectionTemplateId)
                .orderByDesc(InspectionTask::getCreateTime);
        wrapper = QueryHelp.getPredicateEx(wrapper, InspectionTask.class, pageEntity);
        Page<InspectionTaskVo> userList = inspectionTaskMapper.selectJoinPage(new Page<>(pageEntity.getCurrentPage(), pageEntity.getPageSize()),   InspectionTaskVo.class, wrapper);
        return userList;
    }

    /**
     * todo需要修改(根据物料主类找质检模板)
     * @param testDto
     * @throws ParseException
     */
    @Override
    @Transactional
    public void addInspectionTask(InspectionTaskDto testDto) throws ParseException {
        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<InspectionTask> wrapper = new MPJLambdaWrapper<InspectionTask>()
                .eq(InspectionTask::getCode, testDto.getCode())
                .ne(InspectionTask::getDelFlag, 1);
        InspectionTask material = inspectionTaskMapper.selectOne(wrapper);
        if(null != material) {
            throw new GlobalException("该material已经存在");
        }

        InspectionTask test2 = new InspectionTask();
        BeanUtils.copyProperties(testDto, test2, new String[]{"id"});
        test2.setDelFlag(false);
        test2.setCreateBy(userName);
        test2.setCreateTime(new Date());
        inspectionTaskMapper.insert(test2);

        //获取质检单数据
        MPJLambdaWrapper<InspectionTemplateItem> wrapper2 = new MPJLambdaWrapper<InspectionTemplateItem>()
                .selectAll(InspectionTemplateItem.class)//查询user表全部字段
                .selectAs( InspectionItem::getSamplingId, InspectionTemplateItemVo::getSamplingId )
                .selectAs(InspectionItem::getFillQty, InspectionTemplateItemVo::getFillQty)
                .selectAs(InspectionItem::getFillType, InspectionTemplateItemVo::getFillType)

                .leftJoin(InspectionItem.class, InspectionItem::getId, InspectionTemplateItem::getInspectionItemId)
                .eq(InspectionTask::getInspectionTemplateId, testDto.getInspectionTemplateId())
                .ne(InspectionTask::getDelFlag, 1);
        List<InspectionTemplateItemVo> inspectionTemplateItems = inspectionTemplateItemMapper.selectJoinList(InspectionTemplateItemVo.class,wrapper2);
//        for(InspectionTemplateItemVo inspectionTemplateItem: inspectionTemplateItems) {
//            InspectionTaskValue inspectionTaskValue = new InspectionTaskValue();
//            inspectionTaskValue.setInspectionTaskId(test2.getId());
//            inspectionTaskValue.setInspectionTemplateItemId(inspectionTemplateItem.getId());
//            inspectionTaskValue.setInspectionTemplateId(inspectionTemplateItem.getInspectionTemplateId());
//            inspectionTaskValue.setDelFlag(false);
//            inspectionTaskValue.setCreateBy(userName);
//            inspectionTaskValue.setCreateTime(new Date());
//            inspectionTaskValueMapper.insert(inspectionTaskValue);
//        }
        //todo::获取所有的samplingId 10-21最新修改
        List<Long> samplingId = inspectionTemplateItems.stream().map(item -> item.getSamplingId()).distinct().collect(Collectors.toList());
        MPJLambdaWrapper<SamplingItem> wrapper3 = new MPJLambdaWrapper<SamplingItem>()
                .in(SamplingItem::getSamplingId, samplingId)
                .ne(InspectionTask::getDelFlag, 1);
        List<SamplingItem> samplingItems = samplingItemMapper.selectList(wrapper3);
        //添加InspectionTaskTemplateSamplingItem数据
        for(InspectionTemplateItemVo inspectionTemplateItem: inspectionTemplateItems) {
            //根据数量查询抽样频次
            //todo:
            Optional<SamplingItem>  optionalSamplingItem = samplingItems.stream().filter(item ->
                    item.getMinSize() < testDto.getQty()
                    && testDto.getQty() <= item.getMaxSize()
                    && item.getSamplingId() == inspectionTemplateItem.getSamplingId()
            ).findFirst();
            Integer countQty = 1;
            SamplingItem samplingItem = new SamplingItem();
            if(optionalSamplingItem.isPresent()) {
                samplingItem = optionalSamplingItem.get();
                countQty = samplingItem.getSampleSize();
            } else {
                countQty = 1;
            }
            for (int i = 0; i < countQty; i++) {
                Integer sequence = i + 1;
                InspectionTaskTemplateSamplingItem inspectionTaskTemplateSamplingItem = new InspectionTaskTemplateSamplingItem();
                inspectionTaskTemplateSamplingItem.setInspectionTaskId(test2.getId());
                inspectionTaskTemplateSamplingItem.setInspectionTemplateItemId(inspectionTemplateItem.getId());
                inspectionTaskTemplateSamplingItem.setInspectionItemId(inspectionTemplateItem.getInspectionItemId());
                inspectionTaskTemplateSamplingItem.setInspectionTemplateId(inspectionTemplateItem.getInspectionTemplateId());
                inspectionTaskTemplateSamplingItem.setFillQty(inspectionTemplateItem.getFillQty());
                inspectionTaskTemplateSamplingItem.setFillType(inspectionTemplateItem.getFillType());
                inspectionTaskTemplateSamplingItem.setSequence(sequence);
                //增加抽样方案字段
                inspectionTaskTemplateSamplingItem.setSamplingId(samplingItem.getSamplingId());
                inspectionTaskTemplateSamplingItem.setDelFlag(false);
                inspectionTaskTemplateSamplingItem.setCreateBy(userName);
                inspectionTaskTemplateSamplingItem.setCreateTime(new Date());
                inspectionTaskTemplateSamplingItemMapper.insert(inspectionTaskTemplateSamplingItem);
            }
        }
    }

    @Override
    public void addInspectionTasks(List<InspectionTaskDto> inspectionTaskDtos)  {

        InspectionTaskCheck inspectionTaskCheck = new InspectionTaskCheck(
                materialTypeMapper,
                samplingMapper,
                samplingItemMapper,
                inspectionTemplateMapper,
                inspectionTemplateItemMapper,
                inspectionTaskMapper,
                inspectionTaskTemplateSamplingItemMapper,
                inspectionTemplateMaterialMapper
        );
        inspectionTaskCheck.initData(inspectionTaskDtos);
        String msg = inspectionTaskCheck.MSG;
        if(msg != "OK")  {
            throw new  GlobalException(inspectionTaskCheck.MSG);
        }
        Map<InspectionTask, List<InspectionTaskTemplateSamplingItem>> inspectionTaskListMap = new HashMap<>();

        inspectionTaskListMap = inspectionTaskCheck.RESULT_MAP;


        for (Map.Entry<InspectionTask, List<InspectionTaskTemplateSamplingItem>> entry : inspectionTaskListMap.entrySet()) {
            InspectionTask inspectionTask = entry.getKey();
            inspectionTaskMapper.insert(inspectionTask);

            List<InspectionTaskTemplateSamplingItem> inspectionTaskTemplateSamplingItems = entry.getValue();
            for(InspectionTaskTemplateSamplingItem inspectionTaskTemplateSamplingItem : inspectionTaskTemplateSamplingItems) {
                inspectionTaskTemplateSamplingItem.setInspectionTaskId(inspectionTask.getId());
                inspectionTaskTemplateSamplingItemMapper.insert(inspectionTaskTemplateSamplingItem);
            }
        }
        System.out.println("====>修改提交===>");
    }

    @Override
    public void updateInspectionTask(InspectionTaskDto testDto) {
        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<InspectionTask> wrapper = new MPJLambdaWrapper<InspectionTask>()
                ;
        InspectionTask inspectionTask = inspectionTaskMapper.selectOne(wrapper);
        if(null == inspectionTask) {
            throw new GlobalException("该InspectionTask不存在");
        }
        BeanUtils.copyProperties(testDto, inspectionTask);
        inspectionTask.setUpdateBy(userName);
        inspectionTask.setUpdateTime(new Date());
        inspectionTaskMapper.updateById(inspectionTask);
    }

    @Override
    public void delInspectionTask(InspectionTaskDto testDto) {
        InspectionTask material = inspectionTaskMapper.selectById(testDto.getId());
        if(null == material) {
            throw new GlobalException("该InspectionTask不存在");
        }
        material.setDelFlag(true);
        inspectionTaskMapper.updateById(material);
    }

    @Override
    public List<InspectionTaskValueVo> getValueTmpByTaskId(InspectionTaskDto testDto) {

        MPJLambdaWrapper<InspectionTaskValue> wrapper = new MPJLambdaWrapper<InspectionTaskValue>()
                .selectAll(InspectionTaskValue.class)//查询user表全部字段
                .selectAs(InspectionItem::getName, InspectionTaskValueVo::getInspectionItemName)
                .selectAs(InspectionTemplateItem::getSequence, InspectionTaskValueVo::getInspectionTemplateItemSequence)
                //记的测试阶段
                .eq(InspectionTaskValue::getDelFlag, 0)
                .eq(null != testDto.getId(), InspectionTaskValue::getInspectionTaskId,testDto.getId())
                .leftJoin(InspectionTemplateItem.class,InspectionTemplateItem::getId,InspectionTaskValue::getInspectionTemplateItemId)
                .leftJoin(InspectionItem.class, InspectionItem::getId, InspectionTemplateItem::getInspectionItemId)
                .orderByDesc(InspectionTemplateItem::getCreateTime);
        List<InspectionTaskValueVo> userList = inspectionTaskValueMapper.selectJoinList(InspectionTaskValueVo.class, wrapper);
        return userList;


    }

    @Override
    public void fillInspectionTaskValue(List<InspectionTaskValueDto> inspectionTaskValueDtos) {
        String userName = SecurityUtils.getUsername();
        List<Long> ids = new ArrayList<>();
        ids = inspectionTaskValueDtos.stream().map(item -> item.getId()).distinct().collect(Collectors.toList());
        MPJLambdaWrapper<InspectionTaskValue> wrapper = new MPJLambdaWrapper<InspectionTaskValue>()
                .in(InspectionTaskValue::getId, ids)
                .eq(InspectionTaskValue::getDelFlag, 0);

        List<InspectionTaskValue>  inspectionTaskValues =    inspectionTaskValueMapper.selectList(wrapper);
        for(InspectionTaskValue inspectionTaskValue: inspectionTaskValues) {
            Optional<InspectionTaskValueDto> optionalInspectionTaskValueDto = inspectionTaskValueDtos.stream().filter(item ->inspectionTaskValue.getId() == item.getId()).findFirst();
            if(optionalInspectionTaskValueDto.isPresent()) {
                InspectionTaskValueDto inspectionTaskValueDto = optionalInspectionTaskValueDto.get();
                inspectionTaskValue.setValue(inspectionTaskValueDto.getValue());
                inspectionTaskValue.setUpdateBy(userName);
                inspectionTaskValue.setUpdateTime(new Date());
                inspectionTaskValueMapper.updateById(inspectionTaskValue);
            }
        }
    }

    @Override
    public void fillInspectionTaskValueExt(List<InspectionTaskValueDto> inspectionTaskValueDtos) {
        String userName = SecurityUtils.getUsername();

        if(null != inspectionTaskValueDtos && inspectionTaskValueDtos.size() > 0 ) {
            List<String> codes = inspectionTaskValueDtos.stream().map(item -> item.getCode()).distinct().collect(Collectors.toList());
            MPJLambdaWrapper<InspectionTaskValue> wrapper = new MPJLambdaWrapper<InspectionTaskValue>()
                    .in(InspectionTaskValue::getCode, codes)
                    .eq(InspectionTaskValue::getInspectionTaskTemplateSamplingItemId, inspectionTaskValueDtos.get(0).getInspectionTaskTemplateSamplingItemId())
                    .eq(InspectionTaskValue::getDelFlag, 0);
            List<InspectionTaskValue>  inspectionTaskValues =    inspectionTaskValueMapper.selectList(wrapper);
            /**
             * 删除之前得数据
             */
            for(InspectionTaskValue inspectionTaskValue : inspectionTaskValues) {
                inspectionTaskValue.setDelFlag(true);
                inspectionTaskValue.setUpdateBy(userName);
                inspectionTaskValue.setUpdateTime(new Date());
                inspectionTaskValueMapper.updateById(inspectionTaskValue);
            }


            /**
             * 插入新得数据
             */
            for(InspectionTaskValueDto inspectionTaskValueDto : inspectionTaskValueDtos) {
                InspectionTaskValue inspectionTaskValue = new InspectionTaskValue();
                BeanUtils.copyProperties(inspectionTaskValueDtos, inspectionTaskValue, new String[]{"id"});
                inspectionTaskValue.setValue(inspectionTaskValueDto.getValue());
                inspectionTaskValue.setCode(inspectionTaskValueDto.getCode());
                inspectionTaskValue.setName(inspectionTaskValueDto.getName());
                inspectionTaskValue.setDelFlag(false);
                inspectionTaskValue.setCreateBy(userName);
                inspectionTaskValue.setUpdateTime(new Date());
                inspectionTaskValueMapper.insert(inspectionTaskValue);
            }
        }
    }


    @Override
    public Map<String, Object> getTmpValueById(InspectionTaskDto testDto) {


        Map<String, Object> maps = new HashMap<>();
        String userName = SecurityUtils.getUsername();
//        List<Long> ids = new ArrayList<>();
//        ids = inspectionTaskValueDtos.stream().map(item -> item.getId()).distinct().collect(Collectors.toList());
        MPJLambdaWrapper<InspectionTaskValue> wrapper = new MPJLambdaWrapper<InspectionTaskValue>()
                .eq(InspectionTaskValue::getInspectionTaskId, testDto.getId())
                .eq(InspectionTaskValue::getDelFlag, 0)
                .orderByDesc(InspectionTask::getCreateTime);
        List<InspectionTaskValue>  inspectionTaskValues =    inspectionTaskValueMapper.selectList(wrapper);
        for(int i = 0; i < inspectionTaskValues.size(); i++ ) {
            maps.put("value" + i, inspectionTaskValues.get(i).getValue());
        }
        return maps;
    }

    @Override
    public List<InspectionTaskValueVo> getFromInspectionTaskTemplateSamplingItemId(InspectionTaskTemplateSamplingItemDto inspectionTaskTemplateSamplingItemDto) {

        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<InspectionTaskValue> wrapper = new MPJLambdaWrapper<InspectionTaskValue>()
                .eq(InspectionTaskValue::getInspectionTaskTemplateSamplingItemId, inspectionTaskTemplateSamplingItemDto.getId())
                .ne(InspectionTask::getDelFlag, 1);
        List<InspectionTaskValueVo>  inspectionTaskValues =    inspectionTaskValueMapper.selectJoinList( InspectionTaskValueVo.class, wrapper);
        return inspectionTaskValues;
    }
}




